﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.WeChat.Dtos.MPMessage;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 公众号消息
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-09-12 
    /// </summary>
    [Route("api/WeChat/MPMessage")]
    public class MPMessageController : BaseApiController
    {
        private MPMessageBll mPMessageBll = new MPMessageBll();
        private MPUserBll mPUserBll = new MPUserBll();

        #region Get
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList([FromQuery] MPMessageListQuery input)
        {
            var pageinput = input.MapTo<PageInput>();
            pageinput.queryJson = new { input.endTime, input.startTime }.ToJson();
            var data = await mPMessageBll.GetList(pageinput);
            var output = new PageResult()
            {
                list = data.list.MapToList<MPMessageListOutput>(),
                pagination = data.pagination
            };
            return Success(output);
        }

        /// <summary>
        /// 公众号用户树
        /// </summary>
        /// <returns></returns>
        [HttpGet("Users")]
        public async Task<ResponseResult> GetTreeViewUsers()
        {
            var data = await mPUserBll.GetList();
            var usersList = data.Select(x => new MPMessageUsersOutput()
            {
                id = x.openid,
                icon = "fa fa-user",
                nickName = x.nickname
            }).ToList();
            return Success(new { list = usersList });
        }
        #endregion 

        #region Post
        /// <summary>
        /// 预览
        /// </summary>
        /// <param name="input">实体</param>
        /// <param name="openId">公众号用户Id</param>
        /// <returns></returns>
        [HttpPost("{openId}/Actions/Preview")]
        public async Task<ResponseResult> Preview(string openId, [FromBody] MPMessagePreviewInput input)
        {
            var entity = input.MapTo<MPMessageEntity>();
            await mPMessageBll.Preview(openId, entity);
            return Success("操作成功");
        }

        /// <summary>
        /// 发送全员
        /// </summary>
        /// <param name="input">实体对象</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ResponseResult> SendGroupMessageByTagId([FromBody] MPMessageSendInput input)
        {
            var entity = input.MapTo<MPMessageEntity>();
            await mPMessageBll.SendGroupMessageByTagId(entity);
            return Success("发送成功");
        }

        /// <summary>
        /// 上传封面
        /// </summary>
        /// <returns></returns>
        [HttpPost("UploadCover")]
        public async Task<ResponseResult> UploadCover()
        {
            var file = Utils.HttpContext.Current.Request.Form.Files[0];
            var ImgType = Path.GetExtension(file.FileName).Replace(".", "");
            if (!this.AllowFileType(ImgType))
            {
                return Error("上传失败，图片格式不允许上传");
            }
            var filePath = ConfigurationKey.TemporaryFilePath;
            var fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + CommonHelper.Guid.ToString() + Path.GetExtension(file.FileName);
            using (var stream = new FileStream(filePath + fileName, FileMode.Create))
            {
                file.CopyTo(stream);
            }
            return Success("上传成功", fileName);
        }

        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        [HttpPost("UploadFile")]
        public async Task<ResponseResult> UploadFile()
        {
            Thread.Sleep(1000);
            var file = Utils.HttpContext.Current.Request.Form.Files[0];
            var fileType = Path.GetExtension(file.FileName).Replace(".", "");
            if (!this.AllowFileType(fileType))
            {
                return Error("上传失败，文件格式不允许上传");
            }
            var _filePath = ConfigurationKey.TemporaryFilePath;
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + CommonHelper.Guid.ToString() + Path.GetExtension(file.FileName);
            using (var stream = new FileStream(_filePath + _fileName, FileMode.Create))
            {
                file.CopyTo(stream);
            }
            var response = new
            {
                fileName = _fileName,
                creatorTime = DateTime.Now
            };
            return Success("上传成功", response);
        }
        #endregion

        #region Method
        /// <summary>
        /// 允许文件类型
        /// </summary>
        /// <param name="fileExtension">文件后缀名</param>
        /// <returns></returns>
        private bool AllowFileType(string fileExtension)
        {
            var isOk = false;
            var allowExtension = ConfigurationKey.MPUploadFileType;
            foreach (var item in allowExtension)
            {
                if (item == fileExtension.ToLower())
                {
                    isOk = true;
                    break;
                }
                else
                {
                    isOk = false;
                }
            }
            return isOk;
        }
        #endregion
    }
}